/**
 * 每行无【编辑/保存】操作按钮，页面统一一个保存按钮，获取整个表格数据进行保存
 * 示例：views\ProductiveProcess\ProcessQualityControl\SubPages\Parallel.js
 */

import React, { useState, useEffect, useCallback, PureComponent } from 'react'
import { Resizable } from 'react-resizable';
import { Table, Input, InputNumber, Popconfirm, Form, Button, Card, Select, Checkbox, Row } from 'antd';
import { withRouter } from 'react-router';

const { Option } = Select

/***
 * 可伸缩列
 */
const ResizeableTitle = props => {
    const { onResize, width, ...restProps } = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (
        <Resizable
            width={width}
            height={0}
            onResize={onResize}
            draggableOpts={{ enableUserSelectHack: false }}
        >
            <th {...restProps} />
        </Resizable>
    );
};


/***
 * 可编辑行
 */
const EditableContext = React.createContext();

class EditableCell extends React.Component {

    renderCell = form => {
        this.form = form;
        const { children, dataIndex, record, title, editing, required } = this.props;
        // const { editing } = this.state;
        // console.log(editing, form, 'editing');
        return editing ? (
            <Form.Item style={{ margin: 0 }}>
                {form.getFieldDecorator(dataIndex + '_' + record.id, {
                    initialValue: record[dataIndex],
                    rules: [{
                        required: required,
                        max: 100,
                        min: 0,
                        message: '字数限制在0~100之间'
                    }]
                })(<Input />)}  {/*  maxLength={100} minLength={0} */}
            </Form.Item>
        ) : (
            <div
            // className="editable-cell-value-wrap"
            // style={{ paddingRight: 24 }}
            >
                {children}
            </div>
        );
    };

    render() {
        const {
            editable,
            dataIndex,
            title,
            record,
            index,
            children,
            editing,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editing ? (
                    <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
                ) : (
                    children
                )}
            </td>
        );
    }
}
const EditableTable = ({ form, rowKey, isEdit, columns, dataSource, allowRowEdit, allowEditable, allowDrafting, ...props }) => {
    const rowKeyProp = rowKey ? rowKey : (row, index) => index;
    const [columnsProps, setColumnsProps] = useState([...columns])
    const [dataSourceProps, setDataSourceProps] = useState(() => dataSource)
    const [selectedColumns, setSelectedColumns] = useState(() => columns.map((item) => item.dataIndex))

    const handleResize = useCallback((index) => {
        return (e, { size }) => {
            setColumnsProps(prev => {
                const nextColumns = [...prev];
                nextColumns[index] = {
                    ...nextColumns[index],
                    width: size.width,
                };
                return nextColumns;
            });
        };
    }, []);

    // 设置筛选列
    const setFilterDropdown = (columns, setTableCols) => {
        const defaultCols = [...columns];
        const optCols = defaultCols.slice(-1) // 操作列
        const withoutOptCols = defaultCols.slice(0, -1) // 排除操作列之外的列
        const options = withoutOptCols.map(item => ({
            label: item.title,
            value: item.dataIndex
        }))
        let defaultChecked = options.map(item => item.value)
        const filterDropdown = () => {
            return (
                <div className={'dynamic-column'}>
                    <Checkbox.Group defaultValue={defaultChecked} onChange={onColumnChange} >
                        {options && options.map((item) => <Row key={item.value}>
                            <Checkbox value={item.value}>{item.label}</Checkbox>
                        </Row>)}
                    </Checkbox.Group>
                </div>
            );
        }
        const onColumnChange = (checkedArr) => {
            setSelectedColumns([...checkedArr, optCols[0].dataIndex]);
        }
        defaultCols[defaultCols.length - 1].filterDropdown = filterDropdown;
        if (allowDrafting) {
            setTableCols(defaultCols.map((col, index) => ({
                ...col,
                onHeaderCell: column => ({
                    width: column.width,
                    onResize: handleResize(index),
                }),
            })));
        } else {
            setTableCols(defaultCols);
        }
    }

    const handleSave = row => {
        const newData = [...dataSource];
        const index = newData.findIndex(item => row.id === item.id);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        allowEditable(row, newData);
        // 设置 setState，会导致表格中多一条重复数据
        // setDataSourceProps(newData);
    };
    const columnsPropsFinally = columnsProps.filter((col) => {
        return selectedColumns.indexOf(col.dataIndex) > -1;
    }).map((col, index) => {
        let colNew = { ...col }
        if (!allowRowEdit && allowDrafting) {
            colNew = {
                ...colNew,
                onHeaderCell: column => ({
                    width: column.width,
                    onResize: handleResize(index),
                }),
            }
        }
        if (allowEditable && colNew.editable) {
            colNew = {
                ...colNew,
                onCell: record => ({
                    record,
                    editable: colNew.editable,
                    required: colNew.required,
                    dataIndex: colNew.dataIndex,
                    title: colNew.title,
                    editing: isEdit,
                }),
            }
        }
        return colNew;
    });
    const components = {
        header: {
            cell: ResizeableTitle,
        },
        body: {
            cell: EditableCell,
        },
    };
    useEffect(() => {
        setDataSourceProps(dataSource);
    }, [dataSource]);

    useEffect(() => {
        if (allowRowEdit) {
            setFilterDropdown(columns, setColumnsProps)
        }
    }, [allowRowEdit, columns]);
    return (
        <EditableContext.Provider value={form}>
            <Table
                className="x-table"
                size="small"
                components={components}
                rowKey={rowKeyProp}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                columns={columnsPropsFinally}
                scroll={{ y: 200, x: 1300 }}
                pagination={false}
                {...props}
            />
        </EditableContext.Provider>
    );
}

export default Form.create()(EditableTable);
